package com.ijiuchuang.jc_localization.model;

import com.ijiuchuang.jc_localization.app.Config;
import com.ijiuchuang.jc_localization.bean.bmob.Banner;
import com.ijiuchuang.jc_localization.bean.bmob.Result;
import com.ijiuchuang.jc_localization.bean.lite.cache.CacheBanner;
import com.ijiuchuang.jc_localization.bean.api.Keji;
import com.ijiuchuang.jc_localization.contract.HomeContract;
import com.ijiuchuang.jc_localization.network.ApiModel;
import com.ijiuchuang.jc_localization.tools.utils.Log;
import com.litesuits.orm.LiteOrm;

import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Veev on 2016/6/18
 *
 * @link 384506557@qq.com
 */
public class HomeModel implements HomeContract.Model {

    private LiteOrm liteOrm = Config.liteOrm;

    @Override
    public void getBannersFromNet(Action1<List<Banner>> action) {
        ApiModel.bmobGetApi()
                .getBanners()
                .map(new Func1<Result<Banner>, List<Banner>>() {
                    @Override
                    public List<Banner> call(Result<Banner> bannerResult) {
                        return bannerResult.results;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.i("onError in homeModel getBannersFromNet: " + throwable.toString());
                    }
                });
    }

    @Override
    public void saveBanners(List<Banner> list) {
        CacheBanner banner = new CacheBanner(list);
        liteOrm.save(banner);
        Log.i("cache : " + liteOrm.query(CacheBanner.class));
        Log.i("net : " + list);
    }

    @Override
    public void getKeji(Subscriber<Keji> subscriber) {
        ApiModel.apiStore()
                .getKeji(10, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    @Override
    public void getKeji(Action1<Keji> action1) {
        ApiModel.apiStore()
                .getKeji(10, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.i("onError in homeModel getKeji: " + throwable.toString());
                    }
                });
    }
}
